<template>
  <n-modal
      v-model:show="props.modalData.show"
      class="custom-card"
      preset="card"
      :style="{ width: '400px' }"
      title="更换分组"
      :bordered="false"
      :segmented="{
      content: 'hard',
      footer: 'hard'
    }"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :label-width="60" :rules="rules">
      <n-form-item label="名称" path="groupId">
        <n-select v-model:value="form.groupId" :options="groupOptions" filterable/>
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="right">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" @click="handleSave">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup>
import {NButton, NForm, NFormItem, NModal, NSelect, NSpace,} from 'naive-ui'
import {ref, watchEffect} from 'vue'
import {useMediaStore} from "@/store/media";
import {reqEditMedia} from "@/api";

const mediaStore = useMediaStore()
const formRef = ref(null)
const emits = defineEmits(['success'])

const props = defineProps({
  modalData: {
    type: Object,
    required: true
  }
})
const form = ref({
  groupId: null
})
const rules = ref({
  groupId: {type: 'number', required: true, message: '请选择', trigger: 'change'}
})
const groupOptions = ref([])

watchEffect(() => {
  if (props.modalData.show) {
    getGroupList()
    form.value.groupId = props.modalData.groupId
  }
})

async function getGroupList() {
  groupOptions.value = mediaStore.getGroupOptionList()
}

function handleClose() {
  props.modalData.show = false
}

function handleSave() {
  if (form.value.groupId === props.modalData.groupId) {
    props.modalData.show = false
    return
  }
  formRef.value.validate(async errors => {
    if (!errors) {
      await reqEditMedia({id: props.modalData.mediaId, groupId: form.value.groupId})
      emits('success')
      props.modalData.show = false
    } else {
      console.log(errors)
    }
  })
}
</script>

<style scoped lang="scss"></style>
